package org.packtracker.server.service;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.packtracker.client.Constants;
import org.packtracker.server.model.PersistentPackage;

public class NotifyService {
	private static final Logger LOG = Logger.getLogger(NotifyService.class.getName());

	NotifyService() {
	}
	
	public void notify(PersistentPackage trackedPackage) {
		sendEmail(trackedPackage);
	}

	private void sendEmail(PersistentPackage trackedPackage) {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(Constants.ADMIN_EMAIL, Constants.ADMIN_NAME));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(trackedPackage.getMailRecipient()));
			msg.setSubject("New status for package " + trackedPackage.getTrackingId());
			msg.setText("Package status has been updated to:\n" + "\"" + trackedPackage.getLastStatus() + "\"" + "\n\nTo see the full log, go to the tracker page at:\n" + trackedPackage.getTrackerUrl() + "\n\nYou can unregister your package or add new ones at " + "http://packtracker.appspot.com" + "\n\nBest regards\nThe PackTracker Team");
			Transport.send(msg);

			LOG.log(Level.INFO, "Mail sent to " + trackedPackage.getMailRecipient() + ".");

		} catch (Exception exception) {
			LOG.log(Level.WARNING, "Was unable to send mail to " + trackedPackage.getMailRecipient() + ".");

			exception.printStackTrace();
		}
	}
}